package com.gitee.elf.core.data

import com.gitee.elf.core.data.Serializer.asData
import com.google.gson.*
import java.lang.reflect.Type
import java.util.concurrent.ConcurrentHashMap

class DataObject : Data {

    val table = ConcurrentHashMap<String, Data>()

    override fun getValue(): Any {
        return table.map {
            it.key to it.value.getValue()
        }.toMap()
    }

    operator fun set(id: String, data: Data) {
        table[id] = data
    }

    operator fun get(id: String): Data? {
        return table[id]
    }

    operator fun minusAssign(id: String) {
        table.remove(id)
    }

    fun forEach(func: (id: String, Data) -> Unit) {
        table.forEach(func)
    }

    override fun toString(): String {
        return table.toString()
    }

    override fun clone(): DataObject {
        val dataObject = DataObject()
        forEach { id, data ->
            dataObject[id] = data.clone()
        }
        return dataObject
    }

    @SerializerType(DataObject::class)
    class Serializer : JsonSerializer<DataObject>, JsonDeserializer<DataObject> {


        override fun serialize(src: DataObject?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
            val jsonObject = JsonObject()

            return com.gitee.elf.core.data.Serializer.toJsonTree(src!!.table)
        }

        override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): DataObject {
            return json!!.asData() as DataObject
        }

    }

}